package com.lzy.sso.cas.authenticator;

import com.lzy.sso.cas.matcher.Matcher;
import com.lzy.sso.cas.pojo.Subject;
import com.lzy.sso.cas.principle.Principle;
import com.lzy.sso.cas.principle.PrincipleBuilder;
import com.lzy.sso.cas.principle.PrincipleContainer;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @Author: lzy
 * @Date: 2022/4/30 22:39
 * @Description: 原来基础上附加基于角色的授权功能
 */
public abstract class Authorization implements Authenticator {
    @Autowired
    protected Realm realm; // 自定义的认证授权方式

    @Autowired
    protected Matcher matcher; // 密码验证器

    /**
     * 认证 提供模板方法
     * 通过后调用acquireRole获取角色信息 子类可以实现
     * 认证授权成功后调用afterAuthentication
     * @param subject 认证主体
     * @return
     */
    @Override
    public Principle login(Subject subject) {
        Subject proto=new Subject(subject.getUsername(),subject.getPassword());
        PrincipleContainer principle=new PrincipleContainer();

        Subject auth = realm.doGetAuthentication(proto,principle);
        boolean match = matcher.match(auth, subject);
        if(!match){
            return null;
        }

        PrincipleBuilder builder=new PrincipleBuilder();
        builder.authSuccess();
        boolean flag = acquireRole(subject, principle);
        if(flag){
            builder.roleSuccess();
        }

        Principle build = builder.build(principle);
        afterAuthentication(build);

        return build;
    }

    /**
     * 模板方法 子类实现获取authorization
     * @param subject
     * @return
     */
    protected abstract boolean acquireRole(Subject subject,PrincipleContainer principle);

    /**
     * 认证成功后的回调
     * @param principle
     */
    public void afterAuthentication(Principle principle){

    }
}
